using System;
using System.Web;
using Toast.Extensions;
using Toast.Filters;
using Toast.HttpHandlers;

namespace Toast.HttpModules
{
    public class ScriptBehindHttpModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.ReleaseRequestState += OnReleaseRequestState;
            context.PostMapRequestHandler += ContextPostMapRequestHandler;
        }

        #endregion

        static void OnReleaseRequestState(object sender, EventArgs e)
        {
            //TODO: Not sure this is the best way 
            if (!HttpContext.Current.Response.ContentType.Contains("text/html"))
                return;

            var key = RequestPackageCache.Insert(RequestContentTable.Contents);

            var pic = RequestContentTable.Contents.ToInjectionDictionary(key);

            HttpContext.Current.Response.Filter = new ContentInjectionFilter(HttpContext.Current.Response.Filter, pic);
        }

        static void ContextPostMapRequestHandler(object sender, EventArgs e)
        {
            var context = ((HttpApplication) sender).Context;
            if (context.Request.Url.PathAndQuery.Contains(Core.ToastCore.HANDLER_FILENAME))
                context.Handler = new ScriptBehindHttpHandler();
        }
    }
}